package logic

import (
	"context"
	"errors"
	"user/models/cache"
	"user/models/mysql"
	"user/pkg"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *userrpc.UpdatePasswordRequest) (*userrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if pkg.Md5(in.OldPassword) != user.Password {
		return nil, errors.New("密码不一致")
	}

	result, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if result != in.SendSmsCode {
		return nil, errors.New("验证码错误")
	}

	user.Password = pkg.Md5(in.NewPassword)
	err = user.UserPassword(mysql.DB, in.Phone)
	if err != nil {
		return nil, errors.New("修改密码失败")
	}
	cache.Rdb.Del(l.ctx, "sendSms"+in.Phone)
	return &userrpc.UpdatePasswordResponse{}, nil
}
